var express=require('express')
var app=express()
var bodyparser=require('body-parser')
var uE=bodyparser.urlencoded({extended:false})
var mongoose=require('mongoose')
var crypto=require("crypto")
var collections=mongoose.model('userinformations',{
    uname:String,
    upsd:String
})
app.use(function(req,res,next){
    res.header('Access-Control-Allow-Origin', '*');

    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');

    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE,OPTIONS');
    next()
})
app.post('/zc',uE,function(req,res){
    var uname=req.body.username 
    var upsd=req.body.userpsd 
    var newupsd=crypto.createHash('md5').update(upsd).digest('hex');
    mongoose.connect("mongodb://127.0.0.1:27017/zcdl",{useNewUrlParser:true},function(err){
        if(err){
            console.log("数据库连接失败")
        }else{
            console.log("数据库连接成功")

            var mes=new collections({
                uname:uname,
                upsd:newupsd
            })

            collections.find({uname:uname}).then((ok)=>{
                console.log(ok)
                if(ok.length==0){
                    mes.save().then((ok)=>{
                        res.send({status:200,message:"数据录入成功",result:1,data:{uname:uname,upsd:newupsd}})   
                       })         
                }else{
                    res.send({status:200,message:"数据录入失败",result:0})
                }
            })
        }
    })
})




app.post('/dl',uE,function(req,res){
    var uname=req.body.username 
    var upsd=req.body.userpsd
    var newupsd=crypto.createHash('md5').update(upsd).digest('hex');
    mongoose.connect("mongodb://127.0.0.1:27017/zcdl",{useNewUrlParser:true},function(err){
        if(err){
            console.log("数据库连接失败")
        }else{
            console.log("数据库连接成功")

            var mes=new collections({
                uname:uname,
                upsd:newupsd
            })

            collections.find({uname:uname,upsd:newupsd}).then((ok)=>{
                console.log(ok)
                if(ok.length==0){
                    res.send({status:200,message:"数据验证失败",result:0})
                            
                }else{
                    res.send({status:200,message:"数据验证成功",result:1,data:{uname:uname,upsd:newupsd}})     
                }
            })
        }
    })
})



app.listen(4444)